{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 加载数据\n",
    "from sklearn.datasets import fetch_openml\n",
    "import numpy as np\n",
    "\n",
    "mnist = fetch_openml('mnist_784')\n",
    "# 标签和训练数据\n",
    "X, y = mnist['data'], mnist['target']\n",
    "\n",
    "# 训练集和测试集建立\n",
    "X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]\n",
    "\n",
    "# 训练集洗牌赋值\n",
    "shuffle_index = np.random.permutation(60000)\n",
    "X_train, y_train = X_train[shuffle_index], y_train[shuffle_index]\n",
    "X_train, y_train = X_train[:60000], y_train[:60000]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(60000, 784)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X_train.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_array = []\n",
    "train_size = X_train.shape[0]\n",
    "# 遍历图片\n",
    "for i in range(train_size):\n",
    "    train_array.append(X_train[i].reshape(28, 28))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "# np.append(train_array[1][1:,:],train_array[1][0:1,:], axis=0).reshape(1,-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def data_en(data_s, direc='u'):\n",
    "    size=len(data_s) \n",
    "    en_ret = np.zeros((size, 784))\n",
    "#     print(size,en_ret.shape)\n",
    "    \n",
    "    if direc == 'u':        \n",
    "        for i in range(size):\n",
    "            trans_data = np.append(data_s[i][1:,:], data_s[i][0:1,:],axis=0)\n",
    "            #将数据转化为一行 n列。\n",
    "            en_ret[i] = trans_data.reshape(1, -1)\n",
    "    elif direc == 'd':\n",
    "        for i in range(size):\n",
    "            trans_data = np.append(data_s[i][-1:,:], data_s[i][:-1,:],axis=0)\n",
    "            en_ret[i] = trans_data.reshape(1, -1)\n",
    "    elif direc == 'l':\n",
    "        for i in range(size):\n",
    "            trans_data = np.append(data_s[i][:,1:], data_s[i][:,0:1],axis=1)\n",
    "            en_ret[i] = trans_data.reshape(1, -1)\n",
    "    elif direc == 'r':\n",
    "        for i in range(size):\n",
    "            trans_data = np.append(data_s[i][:,-1:], data_s[i][:,:-1],axis=1)\n",
    "            en_ret[i] = trans_data.reshape(1, -1)\n",
    "    return en_ret\n",
    "\n",
    "X_trainu = data_en(train_array, 'u')\n",
    "X_traind = data_en(train_array, 'd')\n",
    "X_trainl = data_en(train_array, 'l')\n",
    "X_trainr = data_en(train_array, 'r')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(300000, 784)\n",
      "(300000,)\n"
     ]
    }
   ],
   "source": [
    "X_trainA = np.concatenate((X_train, X_trainu, X_traind, X_trainl, X_trainr), axis=0)\n",
    "y_trainA = np.concatenate((y_train, y_train, y_train, y_train, y_train), axis=0)\n",
    "print(X_trainA.shape)\n",
    "print(y_trainA.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 实例化，测试训练集(移动前)\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "knn_clf = KNeighborsClassifier()\n",
    "knn_clf.fit(X_train, y_train)\n",
    "y_pred = knn_clf.predict(X_test)\n",
    "\n",
    "\n",
    "from sklearn.metrics import precision_score, recall_score,confusion_matrix\n",
    "ps = precision_score(y_test, y_pred, average=None)\n",
    "print('\\nps=', ps, np.average(ps))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 移动后\n",
    "knn_clfA = KNeighborsClassifier()\n",
    "knn_clfA.fit(X_trainA, y_trainA)\n",
    "y_pred = knn_clfA.predict(X_test)\n",
    "\n",
    "\n",
    "psA = precision_score(y_test, y_pred, average=None)\n",
    "print('\\npsA=', psA, np.average(psA))  "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
